package com.zheng.shop.admin.controller.product;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zheng.common.base.BaseController;
import com.zheng.common.validator.DecimalValidator;
import com.zheng.common.validator.LengthValidator;
import com.zheng.common.validator.NotNullValidator;
import com.zheng.shop.common.Enum.ProductStatusType;
import com.zheng.shop.common.constant.ShopResult;
import com.zheng.shop.common.constant.ShopResultConstant;
import com.zheng.shop.common.exception.ShopException;
import com.zheng.shop.dao.model.*;
import com.zheng.shop.rpc.api.ShopProductService;
import com.zheng.shop.rpc.api.ShopSkuAttributeService;
import com.zheng.shop.rpc.api.ShopSkuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: xinqi
 * Date: 2017/12/19
 * Time: 16:01
 */
@Controller
@Api(value = "商品管理", description = "商品管理")
@RequestMapping("/manage/product/sku")
public class SkuController extends BaseController {
    @Autowired
    private ShopSkuService shopSkuService;
    @Autowired
    private ShopSkuAttributeService skuAttributeService;
    @Autowired
    private ShopProductService productService;

    @ApiOperation(value = "商品首页")
    @RequiresPermissions("product:product:read")
    @ResponseBody
    @RequestMapping(value = "/getSku", method = RequestMethod.GET)
    public Object getSku(Integer productId) {
        JSONArray jsonArray = new JSONArray();
        EntityWrapper<ShopSku> shopSkuEntityWrapper = new EntityWrapper<>();
        shopSkuEntityWrapper.where("product_id=" + productId).where("status=" + ProductStatusType.NORMAL.key);
        List<ShopSku> shopSkus = shopSkuService.selectList(shopSkuEntityWrapper);
        EntityWrapper<ShopSkuAttribute> skuAttributeEntityWrapper;
        for (ShopSku sku : shopSkus) {
            JSONObject jsonObject = new JSONObject();
            skuAttributeEntityWrapper = new EntityWrapper<>();
            skuAttributeEntityWrapper.where("sku_id=" + sku.getId());
            List<ShopSkuAttribute> skuAttributeList = skuAttributeService.selectList(skuAttributeEntityWrapper);
            jsonObject.put("sku", sku);
            jsonObject.put("attributes", skuAttributeList);
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }

    @ApiOperation(value = "商品首页")
    @RequiresPermissions("product:product:update")
    @RequestMapping(value = "/editInventory/{id}", method = RequestMethod.GET)
    public String editInventory(@PathVariable("id") Integer id, Model model) {
        ShopSku shopSku = shopSkuService.selectById(id);
        if (null != shopSku) {
            model.addAttribute("sku", shopSku);
        }
        return "/manage/product/product/inventory.jsp";
    }

    @ApiOperation(value = "商品首页")
    @ResponseBody
    @RequiresPermissions("product:product:update")
    @RequestMapping(value = "/addInventory", method = RequestMethod.POST)
    public Object addInventory(@RequestBody JSONObject params) {
        Integer skuId = params.getInteger("skuId");
        Integer inventory = params.getInteger("inventory");
        ComplexResult result = FluentValidator.checkAll()
                .on(inventory, new NotNullValidator("sku库存"))
                .on(new BigDecimal(inventory), new DecimalValidator(0, 10, "sku库存"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new ShopResult(ShopResultConstant.FAILED, result.getErrors().get(0).getErrorMsg());
        }

        ShopSku sku = shopSkuService.selectById(skuId);
        ShopProduct product = productService.selectById(sku.getProductId());
        if (product.getStatus().equals(ProductStatusType.NORMAL.key)) {
            return new ShopResult(ShopResultConstant.FAILED, "请下架sku对应的商品！");
        }
        sku.setInventory(inventory + sku.getInventory());
        if (shopSkuService.updateById(sku)) {
            return new ShopResult(ShopResultConstant.SUCCESS, ShopResultConstant.SUCCESS.getCode());
        }
        return new ShopResult(ShopResultConstant.FAILED, ShopResultConstant.FAILED.getCode());
    }

    @ApiOperation(value = "判断sku是否上架")
    @ResponseBody
    @RequestMapping(value = "/isMarketable", method = RequestMethod.GET)
    public Object isMarketable(Integer skuId, Integer productId) {
        ShopProduct product = null;
        if (null != skuId) {
            ShopSku shopSku = shopSkuService.selectById(skuId);
            productId = shopSku.getProductId();
            product = productService.selectById(productId);
        } else if (null != productId) {
            product = productService.selectById(productId);
        } else {
            return new ShopResult(ShopResultConstant.FAILED, ShopResultConstant.FAILED.getCode());
        }
        if (product.getMarketable()) {
            return new ShopResult(ShopResultConstant.FAILED, ShopResultConstant.FAILED.getCode());
        }
        return new ShopResult(ShopResultConstant.SUCCESS, ShopResultConstant.SUCCESS.getCode());
    }

}
